package ddd.ajava.chapter5.question1.tcp;
import java.net.*;
import java.io.*;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class TcpFileServer {
    public static void main(String args[]) throws IOException{
    	 ServerSocket server=new ServerSocket(7878);
         System.out.println("服务器端已经开启，等待连接...");
         Socket waitClient=server.accept();
         //到客户端的输入输出流
         BufferedReader read=new BufferedReader(new InputStreamReader(waitClient.getInputStream()));
         InputStreamReader in=new InputStreamReader(waitClient.getInputStream());
        	 
         PrintStream write=new PrintStream(waitClient.getOutputStream());    	 
         //到文件的输入输出流
         String fileName=read.readLine();
//         File file=new File("upload",fileName);//得到文件的名字
         File file=new File(fileName);
         PrintStream writeFile=new PrintStream(file);
         PrintWriter wrtie=new PrintWriter(file);
        		 
         //服务端接受客户端的信息
         char[] chars=new char[1024];
         read.read(chars);
         Scanner in2=new Scanner(waitClient.getInputStream());//
         
         //写入文件
         for(int i=0;i<chars.length;i++){
        	  writeFile.print(chars[i]);      	            	
         }
        //服务器返回给客户端的内容        	
          String response="文件已经收到！";
          FileInformation("文件名："+fileName);
          write.println(response);
          write.flush();       	            
        
         //关闭数据流
          read.close();
          write.close();
          writeFile.close();
          waitClient.close(); 
    	  server.close();
    }
    public static void FileInformation(String texts){//显示收到的文本
		JFrame showInfo=new JFrame();
		JPanel jp=new JPanel();
		JTextArea text=new JTextArea(20,20);//文本区
		text.append(texts);//输入
		jp.add(text);
		showInfo.add(jp);
		
		showInfo.setTitle("服务端相应！");
		showInfo.setVisible(true);
		showInfo.setSize(300,100);
		showInfo.setLocation(500, 500);
		showInfo.setDefaultCloseOperation(1);
	}
}
